﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Text;
using Quartz;
using Wicresoft.RDW.Model;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;
using Common.Logging;

namespace Wicresoft.RDW.Service
{
    public class RequestMonitor : IJob
    {
        private static ILog log = LogManager.GetLogger(typeof(RequestMonitor));
        
        public void Execute(JobExecutionContext context)
        {
            OperateOverTimeUnApprovedRequst();
           
        }
        
        /// <summary>
        /// 获取需要审批的请求，并做相应处理
        /// </summary>
        private void OperateOverTimeUnApprovedRequst()
        {
            
            try
            { 
                log.Info("start approve");
                var settings = SysSettingPresent.ApproveWaitingDay;
                double day = 0d;
                if (string.IsNullOrEmpty(settings))
                {
                    day = 2d;
                }
                else
                {
                    day = double.Parse(settings);
                }
              
                var terminalTime = DateTime.Now.AddDays(-day);
                var requestList = RequestPresent.GetList(x => (terminalTime>= x.CreateTime&& x.Status == (int)RequestStatus.Pending));
                log.Info( "requestList length:" + requestList.Count);
                var dns = ConfigurationManager.AppSettings["DNS"];
                var port = int.Parse(ConfigurationManager.AppSettings["RequestPort"]);
                foreach (var request in requestList)
                {

                    log.Info( "requestId：" + request.RequestId + " execute approval");
                    Approve(request.RequestId, dns,port);
                }

                log.Info("execute approval job execute OK");

            }
            catch (Exception e)
            {
               
                log.Error(e.Message);
            }

        }
        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="RequestId"></param>
        /// <param name="dns"></param>
        /// <param name="port"></param>
        private void Approve(int RequestId, string dns,int port)
        {
            var content = new StringBuilder();
            var userNameCN = string.Empty;
            var userNameEN = string.Empty;
            var linkAddress = string.Empty;
            var linkEmail = string.Empty;
            var linkPhone = string.Empty;
            var requst = RequestPresent.GetById(RequestId);
            var requstLab = LabPresent.GetById(requst.LabId);
            if (requstLab == null) requstLab = new Lab();
            var requestUserEmail = RequestPresent.GetRequestUserEmail(requst.RequestUserId);

            RequestPresent.GetUserNameById(requst.RequestUserId, out userNameCN, out userNameEN);
            linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true,port, Language.EN,true);
            RequestPresent.GetEmailPhoneById(RequestId, out linkEmail, out linkPhone);

            content.Append(userNameEN + "^" + requstLab.Name + "^" + requst.RequestDate.Year + "^" + requst.RequestDate.Month + "^"
                    + requst.RequestDate.Day + " " + Utility.Helper.FormateTimeSpan(requst.StartTime) + "^" + linkAddress + "^" + linkEmail + "^" + linkPhone + "^");
            linkAddress = RequestPresent.GetLinkAddressByRequestId(requst.RequestId, dns, true, port, Language.CN, true);
            content.Append(userNameCN + "^" + requstLab.Name + "^" + requst.RequestDate.Year + "^" + requst.RequestDate.Month + "^"
                + requst.RequestDate.Day + " " + Utility.Helper.FormateTimeSpan(requst.StartTime) +  "^" + linkAddress + "^" + linkEmail + "^" + linkPhone);
            RequestPresent.UpdateRequestById(RequestId, (int)(RequestStatus.Approved), string.Empty);
            var ccList = RequestPresent.GetLabManagerAndSiteManagerEmail(requstLab.LabId, requstLab.LocationId);
            if (ccList == null)
            {
                ccList = new List<string>();
            }
            MailPresent.SendMail(EmailTemplate.ApprovedReminder, content.ToString(), requestUserEmail, ccList);
        }
    }
}
